﻿#region Copyright and License
/*==============================================================================
 *  Copyright (c) cndotnet.org Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.cndotnet.org/ucenter
 * ==============================================================================*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace UCenter.Core.Web
{
    public class ViewUtils
    {
        #region Public methods

        /// <summary>
        /// Get virtual path by current HtmlHelper
        /// </summary>
        /// <param name="helper">The current HtmlHelper</param>
        /// <returns></returns>
        public static string GetVirtualPath(HtmlHelper helper)
        {
            string virtualPath = null;
            Controller controller = helper.ViewContext.Controller as Controller;

            if (controller != null)
            {                
                //ViewEngineResult result = FindView(controller.ControllerContext, helper.ViewContext.ViewName);
                WebFormView webFormView = helper.ViewContext.View as WebFormView;

                if (webFormView != null)
                {
                    virtualPath = webFormView.ViewPath;
                }
            }

            return virtualPath;
        }

        /// <summary>
        /// Find view in viewEngine
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="viewName"></param>
        /// <returns></returns>
        public static ViewEngineResult FindView(ControllerContext controllerContext, string viewName)
        {
            ViewEngineResult result = null;

            WebFormViewEngine viewEngine = ViewEngines.Engines.SingleOrDefault() as WebFormViewEngine;

            result = viewEngine.FindView(controllerContext, viewName, "");

            if (result.View == null)
            {
                result = viewEngine.FindPartialView(controllerContext, viewName);
            }

            return result;
        }

        #endregion
    }
}
